package com.mandroid.forecast.activity;

import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteCursorDriver;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQuery;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.mandroid.forecast.business.Weather;
import com.mandroid.forecast.db.ForecastDao;
import com.mandroid.forecast.util.Constants;
import com.mandroid.forecast.util.Utils;
import com.mandroid.forecast.util.XmlParser;

public class ForecastActivity extends Activity {
	
	private static final int MENU_ABOUT=Menu.FIRST;
	
	private static final int MENU_SET=Menu.FIRST + 1;
	
	private static final int MENU_QUIT=Menu.FIRST + 2;
	
	private static final String UNIT_PREFS="Unit_Prefs";
	
	private static final String UNIT="unit";
	
//	private ForecastDao dao;
	
	private EditText locationText;
	
	private Button forecastButton;
	
	private ProgressDialog progress;
	
	private WebView mainContent;
	
	private String location;
	
	private Weather weather;
	
	private Spinner recentQuery;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
//        dao = new ForecastDao(this);
        init();
        forecastButton.setOnClickListener(forecastListener);
    }
    
    
    
    @Override
	protected void onDestroy() {
		super.onDestroy();
//		dao.close();
	}



	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
    	menu.add(0, MENU_ABOUT, 0, "About");
    	menu.add(0, MENU_SET, 0, "Setting");
    	menu.add(0, MENU_QUIT, 0, "Quit");
    	return true;
	}

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
    	switch (item.getItemId()) {
    	case MENU_ABOUT:
    		openOptionsDialog();
    		break;
    	case MENU_SET:
    		openSettingDialog();
    		break;
    	case MENU_QUIT:
    		finish();
    		break;
    	default:
    		break;
    	}
        return true;
    }
    
    private void openSettingDialog() {
    	 Intent intent = new Intent();
    	 intent.setClass(ForecastActivity.this, SettingActivity.class);
    	 startActivity(intent);
    }
    
    private void openOptionsDialog() {
    	new AlertDialog.Builder(this)
    		.setTitle(R.string.about_title)
    		.setMessage(R.string.about_message)
    		.setPositiveButton(R.string.about_ok,
    				new DialogInterface.OnClickListener(){
    					public void onClick(
    						DialogInterface dialoginterface, int i){
    						}
    				})
    		.setNegativeButton(R.string.about_homepage,
    				new DialogInterface.OnClickListener(){
    					public void onClick(
    							DialogInterface dialoginterface, int i){
    								Uri uri = Uri.parse("http://maleoapp.appspot.com/");
    								Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    								startActivity(intent);
    							}
    					}).show();

    }
    
	private Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			progress.hide();
			updateInterface();
		}
    	
    };
    
    private OnClickListener forecastListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			if (locationText != null && locationText.getText()!=null) {
				location = locationText.getText().toString();
				if ( ! Utils.isNullOrEmpty(location)){
					progress.show();
					new Thread(){
						public void run(){
							String woeid = null;
//							dao.queryWoeid(location);
							String locationUrl = Utils.getGeoPlanetUrl(location);
							try {
								InputStream is = Utils.openUrlForInput(locationUrl);
								if (is != null) {
									woeid = XmlParser.handleGeoPlanet(is);
									is.close();
								}
								if (!Utils.isNullOrEmpty(woeid)) {
//									dao.insertLocation(location, woeid);
									String unit = getPreferenceUnit();
									String weatherRequest = Utils.getWeatherUrl(woeid, unit);
									InputStream inputStream = Utils.openUrlForInput(weatherRequest);
									if (inputStream != null){
										weather = XmlParser.handleWeather(inputStream);
										inputStream.close();
									}
								}
								handler.sendMessage(Message.obtain(handler));
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
					}.start();
	
				} else {
					Toast.makeText(ForecastActivity.this, "Where are you from?", Toast.LENGTH_SHORT).show();
				}
			} else {
				Toast.makeText(ForecastActivity.this, "Where are you from?", Toast.LENGTH_SHORT).show();
			}
		}
	};
    
    private void updateInterface(){
    	if(weather == null) {
    		Toast.makeText(ForecastActivity.this, "Weather Info. not found", Toast.LENGTH_SHORT).show();
    		return ;
    	}
    	mainContent.loadData(weather.getContent(), "text/html", "UTF-8");
    }
	
    private void init(){
    	locationText = (EditText)findViewById(R.id.location);
    	forecastButton =(Button)findViewById(R.id.forecast);
//    	recentQuery = (Spinner)findViewById(R.id.recent_query);
    	progress = new ProgressDialog(this);
    	mainContent = (WebView)findViewById(R.id.weather_text);
//    	String createTable = ForecastDao.getCreateTableStatement(Constants.FORECAST_ROID, ForecastDao.COLUMNS);
//    	dao.execSQL(createTable);
    }
    
    private String getPreferenceUnit() {
    	SharedPreferences prefs = getSharedPreferences(UNIT_PREFS, 0);
    	int preferenceUnit = prefs.getInt(UNIT, 0);
    	if (preferenceUnit == 1) {
    		return "c";
    	} else {
    		return "f";
    	}
    }
}